import { Message } from 'element-ui';

export default function({ $axios, redirect, store, error, router, route }) {
    $axios.defaults.timeout = 10000; // 设置超时时间 默认5000

    // $axios.defaults.headers.post['Content-Type'] =
    //     'application/x-www-form-urlencoded';

    $axios.all = function all(promises) {
        return Promise.all(promises);
    };

    $axios.spread = function spread(callback) {
        return function wrap(arr) {
            return callback.apply(null, arr);
        };
    };

    $axios.onRequest(config => {
        if (store.state.user) {
            const { guid, token } = store.state.user;

            if (!config.params) {
                config.params = {};
            }

            config.params.guid = guid;
            config.params.token = token;
        }
    });

    $axios.onResponse(res => {
        const {
            data: { code, msg },
            config
        } = res;

        if (code !== 1000) {
            const params = config.params;

            if (params && params.noMessage) {
                delete params.noMessage;
            } else {
                Message({
                    message: msg,
                    type: 'error',
                    duration: 2000
                });
            }
        }
    });

    $axios.onError(err => {
        if (err.response) {
            // TODO: 上报信息
            if (err.response.status === 404) {
                Message({
                    message: err.response.status,
                    type: 'error',
                    duration: 2000
                });
            }
        }
    });
}
